#include "filelog.h"
#include <QFileInfo>
#include <QFile>
#include <QDateTime>
#include <QDir>
#include <QDebug>
#include <QTextStream>

FileLog::FileLog(const QString &fName, QDir fPath, int mSize, bool enTimeshift, bool ow)
    : fileName(fName)
    , maxSize(mSize)
    , enableTimeshift(enTimeshift)
    , overwrite(ow)
{
    QString timeshift = "";
    QString ts = QDateTime::currentDateTime().toString("yyyy-MM-dd_hh:mm:ss");
    if (enableTimeshift) {
        timeshift = "_" + ts;
    }

    fileName = fName + timeshift + ".log";
    path = fPath.absoluteFilePath(fileName);

    QString compPath = path.absolutePath();
    completePath = compPath;
    qDebug() << "log file complete path: " << completePath;

    QFileInfo fileInfo(completePath);
    if (fileInfo.exists() && overwrite) {
        remove(completePath.toStdString().c_str());
    }

    QStringList data;
    data << "\n\n###############################################################################\n"
         << "# file log start \n"
         << "# " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") + "\n"
         << "# " + completePath + "\n"
         << "###############################################################################\n\n";
    logSave(data.join(""));
}

void FileLog::logSave(const QString &data)
{
    if (!enableToFile) return ;
    this->writeLock.lock();

    this->fileSizeCheck();

    QFile file(completePath);
    file.open(QIODevice::ReadWrite | QIODevice::Append);
    QTextStream stream(&file);
    stream << data;
    file.flush();
    file.close();
    this->writeLock.unlock();
}

bool FileLog::fileSizeCheck()
{
    QFileInfo fileInfo(completePath);
    if (fileInfo.size() > maxSize) {
        remove(completePath.toStdString().c_str());
        return false;
    }
    return true;
}

void FileLog::logEnable(bool enable)
{
    enableToFile = enable;
}
